package com.prj.ufdm.demo.tutorial.mongo;

import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.bson.types.ObjectId;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;

public class GridFsTest {

	public static void main(String[] args) throws Exception {
		
		GridFS gridFS = getGridFs("file_db");
		
		String fileId = "5d32d4e99432c01d600617f0";
		
		String inputFilePath = "D:\\hello.txt";
		String otFilePath = "D:\\hello_out.txt";
		
		GridFSInputFile gridInputFile = writeFile(gridFS, inputFilePath);
		fileId = gridInputFile.getId().toString();
		
		System.out.println("\n 文件上传成功："+gridInputFile);
		
		GridFSDBFile gridDBFile = readFileByObjectId(gridFS,fileId,otFilePath);
		
		System.out.println("\n 文件下载完成："+gridDBFile);
	} 
	
	/**
	 *  写文件 
	 * @param gridFS
	 * @param writeFile
	 * @return
	 * @throws Exception
	 */
	public static GridFSInputFile writeFile(GridFS gridFS,String inputFilePath) throws Exception  {
		GridFSInputFile gridFile = gridFS.createFile(new File(inputFilePath));
		gridFile.save();
		return gridFile;
	}
	
	/**
	 * 读文件
	 * @param gridFS
	 * @param objectId
	 * @throws Exception
	 */
	public static GridFSDBFile readFileByObjectId(GridFS gridFS,String id,String outFilePath) throws Exception {
		GridFSDBFile gridFSDBFile = gridFS.findOne(new BasicDBObject("_id", new ObjectId(id)));
		InputStream inStream = gridFSDBFile.getInputStream();
		File file = new File(outFilePath);
		FileOutputStream fos = new FileOutputStream(file);
		byte [] readBuff = new byte [1024];
		int readLength;
		while( (readLength = inStream.read(readBuff))!=-1) {
			fos.write(readBuff,0,readLength);
			fos.flush();
		}
		if(inStream!=null) inStream.close();
		if(fos!=null) fos.close();
		return gridFSDBFile;
	}
	
	public static GridFS getGridFs(String dbName) {
		MongoClient mongoClient = MongoDBTest.getConnect(MongoDBTest.HOST,MongoDBTest.PORT);
		return new GridFS(mongoClient.getDB(dbName));
	}
}
